import os

import requests
from zhipuai import ZhipuAI
from dotenv import load_dotenv
import sys
from datetime import datetime, timedelta
import time
import json

sys.path.append("")
from services.redis_config import RedisClient  # 确保正确导入 RedisClient 实例
from config.logging import logger


# 第三方接口
class ThirdApiService:
    def __init__(self):
        load_dotenv()
        api_key = os.getenv('ZHIPU_API_KEY')
        if api_key is None:
            raise ValueError("No API key found for ZhipuAI.")
        self.client = ZhipuAI(api_key=api_key)  # 正确传递API密钥
        self.dialogue = []

    async def send_content(self, websocket, user, content):
        # self.dialogue.append({"role": user, "content": content})
        # dialogue_str = "\n".join([f"{item['role']}: {item['content']}" for item in self.dialogue])
        # print(dialogue_str, self.dialogue)
        content_json = json.loads(content)
        logger.info(f"用户提问拆解:{content_json.get('message')}\n")
        response = self.client.chat.completions.create(
            model="glm-4",
            messages=[{"role": user, "content": content_json.get('message')}],
            stream=True,
        )
        full_response = ""
        for chunk in response:
            # self.dialogue.append({"role": "assistant", "content": chunk.choices[0].delta.content})
            full_response += chunk.choices[0].delta.content
        # await websocket.send_text(full_response)
        logger.info(f"用户提问:{content}\n,AI回复：{full_response}")
        return {"message": full_response, "chat": content_json}

    def baidu_access_token(self):
        access_token_url = "https://aip.baidubce.com/oauth/2.0/token"
        params = {
            "grant_type": "client_credentials",
            "client_id": os.getenv('BAIDU_API_KEY'),
            "client_secret": os.getenv('BAIDU_SECRET_KEY')
        }
        # data=json.dumps(params)
        response = requests.post(access_token_url, params=params, headers={
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        })
        data = response.json()
        access_token = data.get('access_token')
        expires_in = data.get('expires_in')
        print('---------------------')
        print(data, access_token, expires_in)
        if access_token and expires_in:
            RedisClient().set_key_with_expiry("baidu_access_token", access_token, self.time_stamp())
            print("Access token saved in Redis.")
        else:
            print("Failed to get access token.")
        return access_token

    def time_stamp(self):
        now = datetime.now()
        future_date = now + timedelta(days=29)
        return int(time.mktime(future_date.timetuple()))

    async def disable_text_check(self, websoket, content):
        access_token = RedisClient().get_key("baidu_access_token")
        if not access_token:
            access_token = self.baidu_access_token()
        if access_token:
            request_url = "https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined"
            params = {"text": content}
            request_url += "?access_token=" + access_token
            response = requests.post(request_url, data=params, headers={
                'content-type': 'application/x-www-form-urlencoded'
            })
            if response.json().get('conclusion') == '合规':
                res = await self.send_content(websoket, 'user', content)
                return res
            else:
                print(response.json())


if __name__ == "__main__":
    third = ThirdApiService()  # 创建一次实例，避免重复实例化
    select_option = input("请选择你要进行的项目：\n1. 违禁词检测\n2. 小红书工具\n")
    if select_option == "2":
        while True:
            # 获取用户输入的问题
            user_question = input("请输入您的问题（输入'退出'以结束）: ")
            if user_question == "退出":
                break  # 如果用户输入“退出”，则结束循环

            # 获取并打印答案
            answer = third.send_content('小红书营销专家', user_question)
            print("回答:", answer)

            # 提问完毕后询问是否继续
            continue_prompt = input("是否要继续提问？(y/n): ")
            if continue_prompt.lower() != 'y':
                break  # 如果用户不继续提问，则结束循环
    elif select_option == "1":
        user_input = input("请输入要检测的文本：")
        third.disable_text_check(user_input)
    else:
        third.baidu_access_token()
